﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LabelView;
using System.Windows.Forms;
using LabelManager2;

namespace Public
{
    public class LabelPrint {
       
        private string _guid = "{3804AEA2-F63B-11D2-870E-00105A2A2169}";
        private ILabelApplication labelApp = null;
        private ILabelDocument labelDocument = null;
       //private LabelPreViewFrm f = new LabelPreViewFrm();
        public LabelPrint() {
            this.labelApp = this.CreateLabelApplication(_guid);
            labelApp.Visible = false;//窗口是否可见
        }

        public LabelPrint(string _guid) {
            this._guid = _guid;
            this.labelApp = this.CreateLabelApplication(_guid);
            labelApp.Visible = false;//窗口是否可见
        }

        /// <summary>
        /// 打开选择标签模版的对话框
        /// </summary>
        /// <returns>返回选择标签的路径</returns>
        public string GetLabelPath() {
            if (null == labelDocument) {
                labelDocument = GetLabelDocument();
            }
            string _LabelName = labelDocument.BrowseLabel();
            return _LabelName;
        }

        /// <summary>
        /// 退出标签打印
        /// </summary>
        public void Dispose() {
            if (null == labelApp) {
                return;
            }
            labelApp.Quit();
        }

        public bool PrintLabel(string lblPath, System.Collections.Hashtable hTable,int PrintQty,bool bPreview,bool bPrint) {
            if (string.IsNullOrEmpty(lblPath)) {
                MessageBox.Show("模版路径为空或不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (hTable == null || hTable.Count <= 0) {
                MessageBox.Show("没有可打印数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return;
            }
            if (null == labelDocument) {
                labelDocument = GetLabelDocument();
            }
            int ind = labelDocument.Open(lblPath, true);
            //Console.WriteLine(labelDocument.Name);//装载文件的名称
            //Console.WriteLine(labelDocument.LabelHeight+"  "+labelDocument.LabelWidth+" "+((ILabelPrinter)labelDocument.LabelPrinter).Name); 
            //labelDocument.Close(ind);
            //PrintLabel() 	Prints the current label with parameters
            //LabelImageSize() 	Gets the current label抯 image size
            //LabelImage ()	Paints the current label抯 image on the user抯 window
            //LabelSetup 	Invokes the Label Setup window
            //SelectPrinter 	Sets the label抯 printer with a name
            //FormFeed 	Sends a form feed to the current label抯 printer
            ILabelFields labelFields = labelDocument.LabelFields as ILabelFields;
            if (labelFields == null) {
                MessageBox.Show("模版上没有可打印字段", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            for (int i = 0; i < labelFields.Count; i++) {
                ILabelField item = labelFields.Item(i) as ILabelField;
                //DataSource:0-fixed 2-link
                //type:0-text 1-box  2-line 3-barcode 4-picture 5-paragraph 6-two-dim-symb
                
                if (!hTable.Contains(item.Name)) {
                    continue;
                }
                //item.Value = _TableXML.ConvertToString(hTable[item.Name]);
                Console.WriteLine("item.DataSource:" + item.DataSource + " item.Name:" + item.Name + " : " + item.Value);
            }

            if (bPreview) {
                
               // f.Width=labelDocument.LabelWidth;
               // f.Height = labelDocument.LabelHeight;
                //f.doc = labelDocument;
                //f.Show();
                //labelDocument.LabelImage((int)f.Handle, true);
                //f.Update();
            }

            if (bPrint) {
              return  Print(PrintQty);
            }

            return false;
        }

        public void Test() {
            LabelPrint lp = new LabelPrint();
            string pth = lp.GetLabelPath();
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht.Add("barcodeTxt", "123456789aaa");
            ht.Add("mItemTxt", "123456789");
            ht.Add("mItemNameTxt", "PCB板");
            ht.Add("mItemModeTxt", "规格1");
            ht.Add("TH006", "TH006");
            ht.Add("Barcode_TH006", "TH0060001");
            ht.Add("TEXT6", "库位1");
            ht.Add("TH008", "批号0001");
            ht.Add("TH009", "TH009");
            lp.PrintLabel(pth, ht, 1, true, false);//可以直接打印，也可以不打印
            lp.Print(1);//打印
        }

        public bool Print(int PrintQty) {
         return   labelDocument.PrintLabel(PrintQty, null, null, null, null, null, null);
        }

  

        private ILabelDocument GetLabelDocument() {
            return labelDocument = labelApp.ActiveDocument() as ILabelDocument;
        }

        private ILabelApplication CreateLabelApplication(string _guid) {
            return GetActiveXObject(_guid) as ILabelApplication;
        }

        private object GetActiveXObject(string _guid) {
            //在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"
            //:依次双击"组件服务"->"计算机"->"我的电脑"->"DCOM配置"
            //Lblvw.Application
            Guid g = new Guid(_guid);
            Type type = Type.GetTypeFromCLSID(g);
            if (type == null) {
                return null;
            }
            object obj = Activator.CreateInstance(type);
            //if (obj == null) {
            //    MessageBox.Show("创建COM对象失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
            return obj;
        }


    }

    public class CodeSoftPrt {
      
        private ApplicationClass lbl = null;
        private Document doc = null;

        public CodeSoftPrt() {
            if (lbl==null) {
                doc = null;
                lbl = new ApplicationClass();
            }
        }

        public bool PrintLabel(string lblPath, System.Collections.Hashtable hTable, int PrintQty) {
            if (string.IsNullOrEmpty(lblPath)) {
                MessageBox.Show("模版路径为空或不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (hTable == null || hTable.Count <= 0) {
                MessageBox.Show("没有可打印数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
         
            lbl.Documents.Open(lblPath, false);// 调用设计好的label文件
            
            //if (null == doc) {
                doc = lbl.ActiveDocument;
            //}

            try {
                foreach (string key in hTable.Keys) {
                    try {
                        Console.WriteLine(key + ":" + (hTable[key]).ToString());
                        doc.Variables.FormVariables.Item(key).Value = (hTable[key].ToString());
                    } catch (Exception e1) {

                        throw new Exception("key:" + key + "," + e1.Message + ",此错误通常都是模板没有此变量:" + key + "造成！");
                        
                    }
                }
                doc.PrintDocument(PrintQty);
            } catch (Exception ex){
                MessageBox.Show("错误:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            finally {
                lbl.Quit(); //退出
                
            }
            
            return true;
        }

    }

    public class CodeSoftPrt2
    {
        //private TableXML _TableXML = new TableXML();
        private ApplicationClass lbl = new ApplicationClass();
        /// <summary>
        /// 释放打印线程
        /// </summary>
        public void Quit()
        {
            try
            {
               lbl.Quit();
            }
            catch (Exception)
            { }
        }

        public bool PrintLabel(string lblPath, System.Collections.Hashtable hTable, int PrintQty,string _cboPrinters)
        {
            if (string.IsNullOrEmpty(lblPath))
            {
                MessageBox.Show("模版路径为空或不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (hTable == null || hTable.Count <= 0)
            {
                MessageBox.Show("没有可打印数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (string.IsNullOrEmpty(_cboPrinters))
            {
                MessageBox.Show("请选择指定的打印机", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

           try {
              
               if (lbl.ActiveDocument == null || lbl.ActiveDocument.FullName != lblPath)
                {
                    lbl.Documents.CloseAll();
                    lbl.Quit();
                    lbl = new ApplicationClass();
                    lbl.Documents.Open(lblPath, false);// 调用设计好的label文件
               
                    if (lbl.ActiveDocument.Printer.SwitchTo(_cboPrinters))
                    {
                    }
                    else
                    {
                        MessageBox.Show("指定打印机:" + _cboPrinters + "失败！");
                        return false;
                    }

                }
                foreach (string key in hTable.Keys)
                {
                    try
                    {

                        Console.WriteLine(key + ":" + (hTable[key]).ToString());
                        lbl.ActiveDocument.Variables.FormVariables.Item(key).Value = (hTable[key]).ToString();
                    }
                    catch (Exception e1)
                    {
                        throw new Exception("key:" + key + "," + e1.Message + ",此错误通常都是模板没有此变量:" + key + "造成！");
                        return false;
                    }
                }
               
                lbl.ActiveDocument.PrintDocument(PrintQty);

                //打印完后清空参数值
                foreach (string key in hTable.Keys)
                {
                    try
                    {
                        lbl.ActiveDocument.Variables.FormVariables.Item(key).Value = "";
                    }
                    catch (Exception e1)
                    {
                        throw new Exception("key:" + key + "," + e1.Message + ",此错误通常都是模板没有此变量:" + key + "造成！");
                        return false;
                    }
                }
            }
             catch (Exception ex)
             {
                 MessageBox.Show("错误:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return false;
             }
            return true;
        }

        //指定打印机打印
        string _path_str = "";
        public bool PrintLabel(string lblPath, System.Collections.Hashtable hTable, int PrintQty, string _打印机名称,out string msg)
        {
            msg = "";
            if (string.IsNullOrEmpty(lblPath))
            {
                msg = "模版路径为空或不存在";
                return false;
            }
            if (hTable == null || hTable.Count <= 0)
            {
                 msg = "没有可打印数据";
                return false;
            }
            try
             {
                if (lbl.ActiveDocument == null || lbl.ActiveDocument.Printer.Name != _打印机名称 || lbl.ActiveDocument.FullName != lblPath)
                {
                    lbl.Documents.CloseAll();
                    lbl.Quit();
                    lbl = new ApplicationClass();
                    lbl.Documents.Open(lblPath, false);// 调用设计好的label文件
                    if (lbl.ActiveDocument.Printer.SwitchTo(_打印机名称))
                    {
                        // int ttt = 0;
                    }
                    else
                    {
                         msg = "指定打印机:" + _打印机名称 + "失败！";
                        return false;
                        // int ttt = 0;
                    }

                }
                foreach (string key in hTable.Keys)
                {
                    try
                    {

                        Console.WriteLine(key + ":" + (hTable[key]).ToString());
                        lbl.ActiveDocument.Variables.FormVariables.Item(key).Value = (hTable[key].ToString());
                    }
                    catch (Exception e1)
                    {
                        msg = "key:" + key + "," + e1.Message + ",此错误通常都是模板没有此变量:" + key + "造成！";
                       return false;
                    }
                }
                lbl.ActiveDocument.PrintDocument(PrintQty);

                //打印完后清空参数值
                foreach (string key in hTable.Keys)
                {
                    try
                    {
                        lbl.ActiveDocument.Variables.FormVariables.Item(key).Value = "";
                    }
                    catch (Exception e1)
                    {
                        msg = "key:" + key + "," + e1.Message + ",此错误通常都是模板没有此变量:" + key + "造成！";
                        return false;
                    }
                 }
              } catch (Exception ex){
                msg = "错误:" + ex.Message;
                return false;
             }
            return true;
        }

    }

}
